package com.labofjet.blogv3.service.impl;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;

import com.labofjet.blogv3.dao.IArticalDao;
import com.labofjet.blogv3.model.Artical;

@Service
public class ArticalService {
	@Autowired
	private IArticalDao dao;

	/**
	 * 输出顶置文章 按等级倒叙 日期倒叙 id倒叙 排序
	 * 
	 * @return
	 */
	@Cacheable(value = "top-artical", key = "'all'")
	public Page<Artical> findAllTopArticals() {
		return dao.findByLevelInAndIsDelete(Arrays.asList(1, 2, 3), false, new PageRequest(0, 10, new Sort(new Order(
				Direction.DESC, "level"), new Order(Direction.DESC, "date"), new Order(Direction.DESC, "id"))));
	}

	/**
	 * 输出普通文章 按日期倒叙排序 id倒叙 每页5篇
	 * 
	 * @return
	 */
	@Cacheable(value = "artical", key = "'page_' + #currentPage")
	public Page<Artical> findArticals(int currentPage) {
		return dao.findByLevelInAndIsDelete(Arrays.asList(0), false, new PageRequest(currentPage, 5, new Sort(
				new Order(Direction.DESC, "date"), new Order(Direction.DESC, "id"))));
	}

	/**
	 * 根据关键字搜索文章 按日期倒叙排序 id倒叙 每页5篇
	 * 
	 * @return
	 */
	public Page<Artical> findKeywordArticals(String keyword, int currentPage) {
		keyword = "%" + keyword + "%";
		return dao.findByTitleLikeOrIntroductionLikeOrRawContentLikeOrAuthor_UserNameLikeAndIsDelete(keyword, keyword,
				keyword, keyword, false, new PageRequest(currentPage, 5, new Sort(new Order(Direction.DESC, "date"),
						new Order(Direction.DESC, "id"))));
	}

	public Page<Artical> findCategoryArticals(String keyword, int currentPage) {
		return dao.findByCategories_ContentAndIsDelete(keyword, false, new PageRequest(currentPage, 5, new Sort(
				new Order(Direction.DESC, "date"), new Order(Direction.DESC, "id"))));
	}

	@Cacheable(value = "artical", key = "#id")
	public Artical findArtical(long id) {
		return dao.findOne(id);
	}

	@Caching(evict = { @CacheEvict(value = "top-artical", allEntries = true),
			@CacheEvict(value = "artical", allEntries = true) })
	public void save(Artical artical) {
		dao.save(artical);
	}

}
